<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
</head>
<script>
    function onclickbtn_1_internal(_id) {
        tabPanes = document.querySelectorAll('.tab-widget_1_internal .tab-pane_1_internal');
        tabButtons = document.querySelectorAll('.tab-widget_1_internal .tab-button_1_internal');
        for (i = 0; i < tabButtons.length; i++)
            tabButtons[i].classList.remove('active');
        for (i = 0; i < tabPanes.length; i++)
            tabPanes[i].classList.remove('active');

        document.getElementById(_id).classList.add('active');

        tabId = document.getElementById(_id).getAttribute('data-tab');
        tabPane = document.getElementById(tabId);
        tabPane.classList.add('active');
    }
</script>
<style>
    :root {
        --tab-pane_1_internal-padding: 10px
    }

    .centerdiv_1_internal {
        display: flex;
        justify-content: center;
    }

    .tab-widget_1_internal .tab-button_1_internals_1_internal {
        display: flex;
    }

    .tab-widget_1_internal .tab-button_1_internal {
        padding: 1em;
        font-size: 2em;
        background-color: #cccccccc;
        border: none;
        cursor: pointer;
        display: inline-block;
        line-height: 20px;
    }

    .tab-widget_1_internal .tab-button_1_internal.active {
        background-color: #cccccc44;
    }

    .tab-widget_1_internal .tab-content_1_internal .tab-pane_1_internal {
        display: none;
        padding: var(--tab-pane_1_internal-padding);
    }

    .tab-widget_1_internal .tab-content_1_internal .tab-pane_1_internal.active {
        display: block;
    }
</style>
<style>
    .search-container {
        display: flex;
        width: 100%;
        max-width: 600px;
        margin: auto;
        margin-bottom: 10px;
    }
    @media (max-width: 1200px) {
        .search-container {
            max-width: 70%;
        }
    }

    .search-input {
        padding: 20px;
        font-size: 2em;
        border: 1px solid #ddd;
        border-radius: 4px 0 0 4px;
        width: 100%;
        outline: none;
    }

    .search-button {
        padding: 20px;
        background-color: #4285f4;
        color: white;
        border: none;
        cursor: pointer;
        font-size: 2em;
    }

    .search-button:hover {
        background-color: #3367d6;
    }
</style>
<script>
    function read() {
        const url = new URL('/api/tts', window.location.origin);
        url.searchParams.append('text', document.getElementById('searchInput').value)
        const audio = new Audio(url.toString());
        audio.play()
    }
    function performSearch() {
        const url = new URL(window.location.pathname, window.location.origin);
        url.searchParams.append('word', document.getElementById('searchInput').value)
        console.log(url.toString())
        window.location = url.toString()
    }
    async function pasteAndSearch() {
        try {
            const text = await navigator.clipboard.readText();
            if (text && text.trim().length > 0) {
                const input = document.getElementById('searchInput');
                input.value = text.trim();

                setTimeout(() => input.select(), 10);

                performSearch();
            } else {
                alert("剪切板是空的！");
            }
        } catch (e) {
            alert("无法读取剪切板，请确认授权。");
            console.error(e);
        }
    }
</script>
<div class="search-container">
    <input type="text" class="search-input" id="searchInput">
    <button class="search-button" onclick="performSearch()">
        <svg width="30" height="30" viewBox="0 0 30 30" fill="none"
            xmlns="http://www.w3.org/2000/svg" stroke="currentColor" stroke-width="2">
            <circle cx="11" cy="11" r="8" />
            <path d="M21 21L16.65 16.65" />
        </svg></button>
    <button class="search-button" onclick="read()">
        <svg width="30" height="30" viewBox="0 0 30 30" fill="none" 
            xmlns="http://www.w3.org/2000/svg" stroke="currentColor" stroke-width="2">
            <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>
            <path d="M15.54 8.46a5 5 0 0 1 0 7.07"></path>
            <path d="M19.07 4.93a10 10 0 0 1 0 14.14"></path>
        </svg></button>
    <button class="search-button" onclick="pasteAndSearch()">
        <svg width="30" height="30" viewBox="0 0 30 30" fill="none" 
            xmlns="http://www.w3.org/2000/svg" stroke="currentColor" stroke-width="2">
            <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
            <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
        </svg>
    </button>
</div>
<div class="tab-widget_1_internal">
    <div class="centerdiv_1_internal" id="btnsdiv">
        <div> </div>
    </div>
    <div>
        <div class="tab-content_1_internal" id="contentsdiv"> </div>
    </div>
</div>
<script>
    async function fetchSSE(url, onMessage) {
        const response = await fetch(url, {
            headers: { 'Accept': 'text/event-stream' }
        });

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split('\n');
            buffer = lines.pop();

            for (const line of lines) {
                if (line.startsWith('data:')) {
                    const data = line.replace(/^data:\s*/, '').trim();
                    if (data) onMessage(data);
                }
            }
        }
    }
    const currentUrl = new URL(window.location.href);
    currentUrl.pathname = '/api/dictionary';
    const newUrl = currentUrl.toString();
    var idx = 0

    function _runScript(script) {
        let newScript = document.createElement('script');
        newScript.innerHTML = script.innerHTML;
        let src = script.getAttribute('src');
        if (src) newScript.setAttribute('src', src);
        document.head.appendChild(newScript);
        document.head.removeChild(newScript);
    }
    function _setHTMLWithScript(container, rawHTML) {
        container.innerHTML = rawHTML;
        let scripts = container.querySelectorAll('script');
        for (let script of scripts) {
            try {
                _runScript(script);
            } catch (e) {
                console.error(e)
            }
        }
        return scripts.length
    }
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('__internal')) {
        document.body.style.margin = 0
        document.querySelector('.search-container').style.display = 'none'
        document.documentElement.style.setProperty('--tab-pane_1_internal-padding', '0')
    }
    const word = urlParams.get('word');
    if (word) {
        document.getElementById('searchInput').value = word
        fetchSSE(newUrl, (data) => {
            data = JSON.parse(data)
            klass2 = "tab-pane_1_internal"
            klass1 = "tab-button_1_internal"
            if (idx == 0) {
                klass2 += " active"
                klass1 += " active"
            }
            idx += 1
            document.getElementById('btnsdiv').innerHTML +=
                `<button type="button" onclick="onclickbtn_1_internal('buttonid_1_internal${idx}')" id="buttonid_1_internal${idx}" class="${klass1}" data-tab="tab_1_internal${idx}">${data.name}</button>`
            let div = document.createElement('div')
            div.className = klass2
            div.id = `tab_1_internal${idx}`
            document.getElementById('contentsdiv').appendChild(div)
            let div2 = document.createElement('div')
            //对于存在script的，shadow里面没法运行script，只好退而求其次放在外面。目前为止这样做没有问题。
            if (data.result.includes(`<script>`)) {
                div.appendChild(div2)
                _setHTMLWithScript(div2, data.result)
            }
            else {
                div2.innerHTML = data.result
                let shadow = div.attachShadow({ mode: 'open' });
                shadow.appendChild(div2);
            }
        });
    }

    document.getElementById('searchInput').addEventListener('keydown', function (e) {
        if (e.key === 'Enter') {
            performSearch();
        }
    });
</script>